package com.quectel.cms.controller.resource;


import com.quectel.cms.controller.BaseController;
import com.quectel.cms.vo.resource.GetResourcesVo;
import com.quectel.cms.vo.resource.SaveResourcesVo;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.device.dto.DeviceCategoryDto;
import com.quectel.core.module.device.dto.DeviceTypeDto;
import com.quectel.core.module.device.service.DeviceCategoryService;
import com.quectel.core.module.device.service.DeviceTypeService;
import com.quectel.core.module.resource.dto.ResourceGroupDto;
import com.quectel.core.module.resource.service.ResourceGroupService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author rananxin
 * @date 2021-12-08 16:11:40
 */
@RestController
@RequestMapping("resourceGroup")
@Tag(name = "ResourceGroupController", description = "资源组相关api")
public class ResourceGroupController extends BaseController {

    @DubboReference
    private ResourceGroupService resourceGroupService;
    @DubboReference
    private DeviceTypeService deviceTypeService;
    @DubboReference
    private DeviceCategoryService deviceCategoryService;

    @PostMapping("updateResources")
    @RequirePermissions(values = "resourceGroup:edit")
    @Operation(summary = "更新资源关系")
    public Response<Object> updateResources(@RequestBody SaveResourcesVo saveResourcesVo) {
        Long resourceGroupId = saveResourcesVo.getResourceGroupId();
        resourceGroupService.updateResources(resourceGroupId, saveResourcesVo.getCategoryIds(), saveResourcesVo.getTypeIds());

        return Response.ok();
    }

    @GetMapping("getResources")
    @RequirePermissions(values = "resourceGroup:edit")
    @Operation(summary = "根据resourceGroupId获取资源")
    public Response<GetResourcesVo> getResources(@RequestParam Long resourceGroupId) {

        GetResourcesVo result = new GetResourcesVo();
        ResourceGroupDto resourceGroupDto = resourceGroupService.selectById(resourceGroupId);
        if (resourceGroupDto == null) {
            return Response.<GetResourcesVo>ok().wrap(result);
        }
        Long[] cIds = resourceGroupDto.getDeviceCategorys().stream().map(o -> o.getId()).toArray(Long[]::new);
        Long[] tIds = resourceGroupDto.getDeviceTypes().stream().map(o -> o.getId()).toArray(Long[]::new);
        result.setCategorySelected(cIds);
        result.setTypeSelected(tIds);

        Map<String, Object> params =
                Request.parseParams(httpServletRequest);
        super.fillAuthorityData(params);

        List<DeviceCategoryDto> deviceCategoryDtos = deviceCategoryService.queryList(params);
        List<DeviceTypeDto> deviceTypeDtos = deviceTypeService.queryList(params);

        List<GetResourcesVo.TransferItem> categoryTransferData = deviceCategoryDtos.stream().map(o -> {
            GetResourcesVo.TransferItem transferItem = new GetResourcesVo.TransferItem();
            transferItem.setKey(o.getId());
            transferItem.setLabel(o.getName());
            return transferItem;
        }).collect(Collectors.toList());
        result.setCategoryResources(categoryTransferData);

        List<GetResourcesVo.TransferItem> typeTransferData = deviceTypeDtos.stream().map(o -> {
            GetResourcesVo.TransferItem transferItem = new GetResourcesVo.TransferItem();
            transferItem.setKey(o.getId());
            transferItem.setLabel(o.getName());
            return transferItem;
        }).collect(Collectors.toList());
        result.setTypeResources(typeTransferData);

        return Response.<GetResourcesVo>ok().wrap(result);
    }

    /**
     * 资源组分页查询列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "resourceGroup:list")
    @Operation(summary = "资源组分页查询列表")
    public Response<Page<ResourceGroupDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest))
                .like("name");

        super.fillAuthorityData(request.getParams());
        int total = resourceGroupService.queryTotal(request.getParams());

        List<ResourceGroupDto> list = null;
        if (total > 0) {
            list = resourceGroupService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<ResourceGroupDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<ResourceGroupDto>>ok().wrap(page);
    }


    /**
     * 查询资源组单条记录
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "resourceGroup:info")
    @Operation(summary = "查询资源组单条记录")
    public Response<ResourceGroupDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (resourceGroupService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ResourceGroupDto resourceGroupDto = resourceGroupService.selectById(id);

        return Response.<ResourceGroupDto>ok().wrap(resourceGroupDto);
    }

    /**
     * 保存资源组单条记录
     */
    @PostMapping("save")
    @RequirePermissions(values = "resourceGroup:edit")
    @Operation(summary = "保存资源组单条记录")
    public Response<Object> save(@RequestBody @Validated ResourceGroupDto resourceGroupDto) {

        //填充基础数据
        fillSaveCommonData(resourceGroupDto);

        resourceGroupService.save(resourceGroupDto);

        return Response.ok();
    }

    /**
     * 修改资源组单条记录
     */
    @PostMapping("update")
    @RequirePermissions(values = "resourceGroup:edit")
    @Operation(summary = "修改资源组单条记录")
    public Response<Object> update(@RequestBody @Validated ResourceGroupDto resourceGroupDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(resourceGroupDto.getId()));
        if (resourceGroupService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(resourceGroupDto);

        resourceGroupService.updateById(resourceGroupDto);

        return Response.ok();
    }

    /**
     * 批量删除资源组记录
     */
    @PostMapping("delete")
    @RequirePermissions(values = "resourceGroup:delete")
    @Operation(summary = "批量删除资源组记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (resourceGroupService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        resourceGroupService.deleteBatch(ids);

        return Response.ok();
    }
}
